<template>
  <view class="view-class">
    <u-navbar back-text="返回" title="账单信息"></u-navbar>
    <view class="view-box">
      <u-form :model="form" ref="uForm" label-width="180" label-align="center">
        <u-form-item v-for="(item,index) in formParams"  :label="item.label" :prop="item.prop" v-if="(item.prop != 'realityCheckOutAmount' && activeType == 0 ) || (item.prop != 'totalAmount' && activeType == 1 )">
          <u-input disabled v-model="form[item.prop]" :disabled="!isAdmin || (isAdmin && item.disabled == true)"/>
        </u-form-item>
<!--        <u-form-item  label="共计" prop="totalAmount" v-if="!isAdmin">-->
<!--          <u-input class="all-num"  :field-style="{fontWeight: 550,color: '#fa3534'}" disabled v-model="totalAmount" disabled/>-->
<!--        </u-form-item>-->
      </u-form>
      <u-button style="position: fixed;bottom: 0;left: 0;width: 100%;z-index: 9" type="primary" @click="submitFunc" v-if="isAdmin && form.confirmStatus!=1">账单确认</u-button>
      <u-button style="position: fixed;bottom: 0;left: 0;width: 100%;z-index: 9" type="primary" @click="submitFunc('pay')" v-else-if="isAdmin!=true && form.isPay != 1 && form.paymentMethod == 1 && form.confirmStatus == 1 && (!form.realityCheckOutAmount || Number(form.realityCheckOutAmount)<0)">确认支付</u-button>
      <u-button style="position: fixed;bottom: 0;left: 0;width: 100%;z-index: 9" type="primary" @click="submitFunc('success')"  v-else-if="form.isPay != 1 && isAdmin!=true && (form.status && form.status != 3) && form.confirmStatus == 0">审核中</u-button>
<!--      <u-button style="position: fixed;bottom: 0;left: 0;width: 100%;z-index: 9" type="primary" @click="submitFunc('success')" v-else>完成</u-button>-->
    </view>
<!--    <u-select v-model="showContactRelationSel" :list="contactRelationList" mode="single-column"-->
<!--              @confirm="selectedContactRelation"></u-select>-->
<!--    <u-calendar v-model="calendarShow" :mode="mode" :default-start-date="minDate" :min-date="minDate" :max-date="'2099-1-1'" @change="changeCalendar"></u-calendar>-->
    <u-modal v-model="showModal" :content="content" :show-cancel-button="true" :confirm-text="'已支付'" :cancel-text="'未支付'"  :confirm-color="'#fff'" :confirm-style="{background:'#19be6b'}" @confirm="confirmFunc"></u-modal>
    <u-top-tips ref="uTips"></u-top-tips>
    <u-modal v-model="showModel" :content="showContent" @confirm="submitData" @cancel="cancel" show-cancel-button></u-modal>
  </view>
</template>

<script>
import {compressImg} from '@/utils/compressor/compress.js'
import {uploadImg} from '@/utils/upload.js'
// import uniRate from '@/uni_modules/uni-rate/'






export default {
  data() {
    return {
      showModel: false,
      showContent:'',
      showModal:false,
      content:'是否支付完成',
      form:{},
      formParams:[
        {label:'姓名',prop:'name',disabled:true},
        {label:'电话',prop:'phoneNumber',disabled:true},
        // {label:'ID',prop:'riderId'},
        {label:'部门/站点',prop:'deptName',disabled:true},
        {label:'身份证号',prop:'idCardNo',disabled:true},
        {label:'房间号',prop:'roomNo',disabled:true},
        {label:'床位号',prop:'bedNo',disabled:true},
        {label:'押金',prop:'deposit'},
        {label:'租金/日',prop:'rent'},
        {label:'水费',prop:'waterRate'},
        {label:'电费',prop:'electricCharge'},
        {label:'燃气费',prop:'gasCost'},
        {label:'取暖费',prop:'heatingFee'},
        {label:'维修费',prop:'maintenanceCost'},
        {label:'其他费用',prop:'otherExpenses'},
        // {label:'总金额',prop:'totalAmount'},
        {label:'实际退宿结余',prop:'realityCheckOutAmount'},
      ],
      isAdmin:false,
      form1:{},
      form2:{},
      activeType:0,
      urlQuery:{},
      doubleClick:false
    };
  },
  async onLoad(query) {
    // query.billId= 37
    await this.init(query)
    console.log('22222222222222222222222222222',this.isAdmin!=true && this.form.isPay != 1 && this.form.paymentMethod == 1 && this.form.confirmStatus == 1 && (!this.form.realityCheckOutAmount || parseInt(this.form.realityCheckOutAmount)<0),Number(this.form.realityCheckOutAmount)<0)
  },
  created() {
    const oScript = document.createElement('script');
    oScript.type = 'text/javascript';
    oScript.src = 'https://res2.wx.qq.com/open/js/jweixin-1.6.0.js';
    document.body.appendChild(oScript);
    oScript.onload = this.wxmini
  },
  methods:{
    async init(query) {
      this.urlQuery = query
      this.activeType = query.activeType
      let openId = uni.getStorageSync('openId')
      await this.getBillInfoById(query.billId)
      await this.getLodgingInfoById(query.id)
      console.log(JSON.parse(JSON.stringify(this.form1)),JSON.parse(JSON.stringify(this.form2)))
      this.form = Object.assign({},this.form2,this.form1)
      this.form.deptName = this.form.deptName?this.form.deptName:'无'
      this.formParams.forEach(v =>{
        if (v.label.includes('费')){
          this.form[v.prop] = this.form[v.prop]?this.form[v.prop]:0
        }
      })
      console.log('JSON.stringify(this.form)=====>>>>',JSON.stringify(this.form))
      this.isAdmin = JSON.parse(uni.getStorageSync('isAdmin')?uni.getStorageSync('isAdmin'):false)
    },
    async queryOrder() {
      uni.showLoading({
        title: '正在查询支付状态...'
      });
      let { code,msg }  = await this.$api.dormitory.queryOrder(this.form.billId)
      if (code == 200 && msg != 'null') {
        uni.showToast({
          title: '支付成功',
          icon: 'none',
          duration: 2000,
        })
        this.init(this.urlQuery)
      } else{
        uni.showToast({
          title: '支付异常',
          icon: 'none',
          duration: 2000,
        })
      }
    },
    wxmini(){
      var urlString = encodeURIComponent(location.href.split('#')[0])
      console.log(urlString)
      // 获取密钥
      this.$api.dormitory.getSdk(urlString).then(res=>{
        if (res.code == 300){
          this.wxmini()
        }
        const configData = res.data
        jWeixin.config({ // eslint-disable-line
          // debug: true,
          appId: configData.appid, // 必填，公众号的唯一标识
          timestamp: configData.timestamp, // 必填，生成签名的时间戳
          nonceStr: configData.noncestr, // 必填，生成签名的随机串
          signature: configData.signature,
          jsApiList: ["wx-open-launch-weapp","scanQRCode"], // 必填，需要使用的JS接口列表
          openTagList: ['wx-open-launch-weapp'] // 可选，需要使用的开放标签列表，例如['wx-open-launch-app']
        });

        jWeixin.ready(function () {
          console.log('ready')
        });

        jWeixin.error(function (e) {
          console.log('error',e)
        });
      })
    },
    cancel(){
      this.showModel = false
    },
   async submitData(){
      if (this.isAdmin) {
        this.form.confirmStatus = 1
        let {code} = await this.$api.dormitory.updateRidersBillInfoById(this.form)
        if (code == 200) {
          uni.showToast({
            title: "账单确认成功",
            icon: "none",
          });
          setTimeout(()=>{
            uni.redirectTo({
              url: `/pages/serve/audit/webIndex?type=${this.activeType}`
            })
          },500)
        }
      }
    },
    async confirmFunc() {
      // let {data} = await this.$api.dormitory.inquireOrder({id:this.form.billId})
      // if (data) {
      //   this.form.isPay = 1
      // }

    },
    async getBillInfoById(billId){
      let {data} = await this.$api.dormitory.getBillInfoById(billId)
      if (data) {
        this.form1 = data
        this.form1.billId = data.id

      }
    },
    async getLodgingInfoById(id){
      let {data} = await this.$api.dormitory.getLodgingInfoById(id)
      if (data) {
        this.form2 = data
      }
    },
    selectedContactRelation(){

    },
    async submitFunc(type) {
      if (type == 'success') {
        if (this.isAdmin == true) {
          uni.redirectTo({
            url: `/pages/serve/audit/webIndex?type=${this.activeType}`
          })
          return
        }
        uni.reLaunch({
          url: `/pages/serve/webIndex`
        })
        return
      }
      if (type == 'pay') {
        let openId = uni.getStorageSync('openId')
        if (this.doubleClick != false ) return
        this.doubleClick = true
        let res  = await this.$api.dormitory.createOrder({id:this.form.billId,openId:openId}).catch(()=>{this.doubleClick = false})
          if (res.code == 200) {
            jWeixin.chooseWXPay({
              //下面参数要与上面对应
              appId: res.data.appId, // 必填，公众号的唯一标识
              timestamp: res.data.timeStamp,
              nonceStr: res.data.nonceStr, // 支付签名随机串，不长于 32 位
              package: res.data.packageValue, // 统一支付接口返回的prepay_id参数值
              signType: res.data.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
              paySign: res.data.paySign, // 支付签名
              success: async (r) => { //支付成功回调
                console.log('支付成功')
                this.queryOrder()
              },
              cancel: function(res) {
                uni.showToast({
                  title: '取消支付',
                  icon: 'none',
                  duration: 2000,
                })
              },
              fail: function(res) {
                console.log("fail", res);
                uni.showToast({
                  title: '支付失败',
                  icon: 'none',
                  duration: 2000,
                })
              }
            });
          }
          this.doubleClick = false
        return
      }
      if (this.activeType == 1) {
        let res = await this.$api.dormitory.selectBillInfoCalculate(this.form);
        this.showContent = `核算金额为${res.msg}元，请确认账单无误后点击确认按钮！`
        this.form.realityCheckOutAmount = res.msg
      } else {
        this.showContent = `请确认账单无误后点击确认按钮！`
      }

      this.showModel = true;

    },
    changeCalendar(e) {
      const nowTime = this.nowTime()
      if (e.result != nowTime) {
        this.form.checkOutTime = e.result
      } else {
        this.form.checkOutTime =  '';
        uni.showToast({
          title: "离宿日期不可选择当天",
          icon: "none",
        });
      }
    },
  }
};
</script>
<style scoped>
*{
  box-sizing: border-box;
}
  .view-class{
    width: 100%;
    height: 100vh;
  }
  .view-box{
    padding:0 30rpx;
    padding-bottom: 120rpx;
  }
  .container {
    height: 200vh;
    margin-top: 150rpx;
  }

  .sticky {
    width: 750rpx;
    height: 120rpx;
    background-color: #2979ff;
    color: #fff;
    padding: 24rpx;
  }
  .u-form-item{
    padding-right: 30rpx;
  }

  /deep/.u-star-wrap{
    line-height: 1;
  }
  .u-form-item{
    padding: 8rpx 0;
  }
  .all-num /deep/input{
    color: #fa3534;
  }
</style>
